package com.sz.app.oss.api.logistics.base;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.logistics.base.entity.WeightSchema;
import com.sz.biz.logistics.base.service.WeightSchemaService;
import com.sz.biz.logistics.base.dto.WeightSchemaDto;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.system.service.SysUserSupport;
import com.sz.common.core.system.service.UserModel;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Function: ExchangeRateController <br>
 * Author: xutao <br>
 * Date: 2017-02-20 10:19:00
 */
@RestController
@RequestMapping("/api/v1/biz/weightschema")
@Api(description = " ", tags = "033、重量区间管理")
public class WeightSchemaController extends BaseController {

    @Autowired
    private WeightSchemaService weightSchemaService;
    @Autowired
    SysUserSupport userSupport;

    /**
     * 新增重量区间
     *
     * @param weightSchemaDto 要保存的数据
     * @return 操作状态
     * @throws Exception 异常信息
     */
    @ApiOperation(value = "新增计重方案", notes = "新增计重方案")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_WEIGHT)
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultDto addWeightPartion(@RequestBody @ApiParam(value = "汇率对象", required = true)
                                      @Validated WeightSchemaDto weightSchemaDto) {

        int id = weightSchemaService.addWeightSection(weightSchemaDto);

        ResultDto resultDto = getSaveSuccessDto(MessagesCodes.MODULE_WEIGHT_SCHEMA);

        resultDto.setData(id);

        return resultDto;
    }

    /**
     * 批量删除
     *
     * @param ids 要删除的id集合
     * @return 操作结果
     */
    @ApiOperation(value = "删除", notes = "删除计重分区方案<br>权限：" + Permissions.BIZ_MGT_BASE_WEIGHT, httpMethod = "POST")
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_WEIGHT)
    public ResultDto batchDelete(@RequestBody @ApiParam(value = "要删除的id集合", required = true) List<Integer> ids) {

        weightSchemaService.deleteWeightSection(ids);

        ResultDto resultDto = getDeleteSuccessDto(MessagesCodes.MODULE_WEIGHT_SCHEMA);

        return resultDto;
    }

    /**
     * 修改
     *
     * @param weightSchemaDto 要修改的对象
     * @return 操作结果
     */
    @RequestMapping(value = "", method = {RequestMethod.PUT})
    @ApiOperation(value = "修改", notes = "修改计重分区方案<br>权限：" + Permissions.BIZ_MGT_BASE_WEIGHT)
    @Transactional(propagation = Propagation.REQUIRED)
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_WEIGHT)
    public ResultDto update(@RequestBody WeightSchemaDto weightSchemaDto) {

        int count = weightSchemaService.updateWeightSection(weightSchemaDto);

        ResultDto result = getUpdateSuccessDto(MessagesCodes.MODULE_WEIGHT_SCHEMA);

        result.setData(count);

        return result;
    }

    /**
     * 根据条件获取数据集合
     *
     * @param q         参数信息
     * @param pageIndex 哪页
     * @param pageSize  分页大小
     * @param sort      排序字段的名称
     * @param asc       true asc false desc
     * @return 查询的数据集合
     */
    @ApiOperation(value = "查询", notes = "根据指定条件获取数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true")
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResultDto find(@RequestParam(required = false) String q,
                          @RequestParam(required = false, defaultValue = "1") int pageIndex,
                          @RequestParam(required = false, defaultValue = "10") int pageSize,
                          @RequestParam(required = false) String sort,
                          @RequestParam(required = false, defaultValue = "true") Boolean asc
    ) {
        q = StringUtils.replaceSqlPattern(q);
        ResultDto resultDto = weightSchemaService.findWeightSection(new QueryParams(pageSize, pageIndex, q, sort, asc));
        List<WeightSchemaDto> dtos = (List<WeightSchemaDto>) resultDto.getData();
        if (dtos != null && dtos.size() > 0) {
            //收集创建者Id
            List<Integer> userIds = new ArrayList<>();
            dtos.forEach(dto -> {
                Integer userid = dto.getCreatorId();
                if (!userIds.contains(userid)) {
                    userIds.add(userid);
                }
            });
            Map<Integer, UserModel> users = userSupport.getUsersMapById(userIds);
            if (users != null && users.size() > 0) {
                dtos.forEach(dto -> {
                    UserModel user = users.get(dto.getCreatorId());
                    if (user != null) {
                        dto.setAccountName(user.getAccountName());
                        dto.setCreator(user.getFullName());
                    }
                });
            }
        }
        return resultDto;
    }

    /**
     * 凭借重量段名称或code获取最大的结束重量值
     *
     * @param id:
     * @return 操作状态
     * @throws Exception 异常信息
     */
    @ApiOperation(value = "获取区间段开始默认值", notes = "获取区间段开始默认值")
    @RequestMapping(value = "defaultBeginPoint", method = RequestMethod.GET)
    public QResultDto getMaxEndPoint(@RequestParam int id) {

        QResultDto qResultDto = weightSchemaService.getMaxEndPoint(id);

        return qResultDto;
    }

    /**
     * 检查code是否重复
     *
     * @param code:
     * @return 操作状态
     * @throws Exception 异常信息
     */
    @ApiOperation(value = "检查code是否重复", notes = "检查code是否重复")
    @RequestMapping(value = "isexistedcode", method = RequestMethod.GET)
    public QResultDto getMaxEndPoint(@RequestParam String code) {

        QResultDto qResultDto = new QResultDto();

        WeightSchema weightSchema = new WeightSchema();

        weightSchema.setCode(code);

        boolean isExist = weightSchemaService.isExistedWeightSchema(weightSchema);

        qResultDto.setData(isExist);

        return qResultDto;
    }

    /**
     * 根据uid获取详细信息
     *
     * @param uid:
     * @return 操作状态
     * @throws Exception 异常信息
     */
    @ApiOperation(value = "根据uid获取详细信息", notes = "根据uid获取详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "uid", required = true, dataType = "string", paramType = "path")})
    @RequestMapping(value = "/{uid}", method = RequestMethod.GET)
    public QResultDto findActivedByUid(@PathVariable String uid) {

        QResultDto qResultDto = new QResultDto();

        WeightSchemaDto weightSchemaDto = weightSchemaService.findActivedByUid(uid);

        qResultDto.setData(weightSchemaDto);

        return qResultDto;
    }
}
